package com.zhou.framework.jwt.interceptor;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.zhou.framework.constant.AppEnum;
import com.zhou.framework.exception.TokenException;
import com.zhou.framework.exception.SessionOutTimeException;
import com.zhou.framework.jwt.annotation.PassToken;
import com.zhou.framework.util.SessionUtil;
import com.zhou.framework.jwt.model.LoginUser;
import com.zhou.org.dao.User;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @author lang.zhou
 * @date 2022/4/29 16:47
 */
public class AuthenticationInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse httpServletResponse, Object object){
        // 从 http 请求头中取出 token
        String token = request.getHeader(AppEnum.TOKEN_KEY);
        // 若果没有加拦截注解，即通过
        if(!(object instanceof HandlerMethod)){
            return true;
        }
        /*String uri = request.getRequestURI();
        if(uri.endsWith("/error/400") || uri.endsWith("/error/401") || uri.endsWith("/error/404")  || uri.endsWith("/error/500") ){
            return true;
        }*/

        HandlerMethod handlerMethod=(HandlerMethod)object;
        Method method=handlerMethod.getMethod();
        // 检查是否有PassToken注释，有则跳过认证
        if (method.isAnnotationPresent(PassToken.class)) {
            return true;
        }

        // 检查是否有 UserLoginToken 注解，如果有，进行拦截
        return verify(token);
    }
    public boolean verify(String token){
        try {
            //从redis中取用户信息，避免每次查询数据库
            LoginUser loginUser = SessionUtil.decodeToken(token);
            User user = loginUser.getUser();
            // 验证 token ，返回 true
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
            jwtVerifier.verify(token);
            //刷新缓存
            SessionUtil.cacheUser(loginUser);
        }catch (TokenExpiredException e) {
            throw new SessionOutTimeException("token过期",e);
        }catch (JWTVerificationException e) {
            throw new TokenException("token校验失败",e);
        }
        return true;
    }
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView){
    }
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e){
    }
}
